package iu.gq.template;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.gq.utils.NetworkState;
import com.gq.widget.actionbar.ActionBarActivity;

public class NoNetworkActivity extends ActionBarActivity {

	private Handler mHandler;
	private ProgressBar mProgressBar;
	private Intent mIntent;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mHandler = new Handler();
		setContentView(R.layout.no_network_layout);
		mIntent = (Intent) getIntent().getExtras().get("INTENT");
		final Button btnRetry = (Button) findViewById(R.id.btn_reconnect);
		mProgressBar = (ProgressBar) findViewById(R.id.progress);
		mProgressBar.setVisibility(View.GONE);
		final TextView label = (TextView) findViewById(R.id.label_no_network);
		
		btnRetry.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View view) {
				mProgressBar.setVisibility(View.VISIBLE);
				label.setVisibility(View.GONE);
				btnRetry.setVisibility(View.GONE);
				if ((new NetworkState(NoNetworkActivity.this)).hasConnection()) {
					mHandler.postDelayed(new Runnable() {
						
						@Override
						public void run() {
							mProgressBar.setVisibility(View.GONE);
						}
					}, 500);
					startActivity(mIntent);
					finish();
				} else {
					mHandler.postDelayed(new Runnable() {
						
						@Override
						public void run() {
							mProgressBar.setVisibility(View.GONE);
							label.setVisibility(View.VISIBLE);
							btnRetry.setVisibility(View.VISIBLE);
						}
					}, 1000);
				}
			}
		});
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater mMenuInflater = getMenuInflater();
		mMenuInflater.inflate(R.menu.none, menu);
		getActionBarHelper().setDisplayHomeAsUpEnabled(true);
		return super.onCreateOptionsMenu(menu);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch(item.getItemId()) {
			case android.R.id.home:
				onBackPressed();
				break;
		}
		return super.onOptionsItemSelected(item);
	}
}
